<template>
  <div class="question-bank-container">
    <micro-app
      v-if="initStatus"
      name="question-bank"
      iframe
      :baseroute="baseURL + '/question-bank'"
      :url="aiQuestionBankWeb"
      :data="microData"
      router-mode="native-scope"
      clear-data
      @datachange="eventListeners"
    />
    <ChapterDrawer
      v-if="isVis"
      v-model:visible="isVis"
      :course="selectCourse"
    />
    <CreateTargetClass
      v-if="createVisible"
      :visible="createVisible"
      :studentList="targetClassParams.students"
      :schoolId="targetClassParams.schoolId"
      :teacherId="userInfo.userId"
      @close="handleClose"
    />
  </div>
</template>

<script setup>
import { onMounted, ref, watch, onUnmounted } from 'vue'
import CreateTargetClass from '@/views/workbench/components/CreateTargetClass.vue'
import ChapterDrawer from '@/components/publish-task/ChapterDrawer.vue'
import { useAuthStore, useTaskStore } from '@/stores'
import { aiQuestionBankWeb } from '@/apis'
import { storeToRefs } from 'pinia'
import { baseURL } from '@/router'
import { ElMessage } from 'element-plus'
import { iframeTaskMitt } from '@/utils/tools/bus'
import { useRoute, useRouter } from 'vue-router'
import { useAILessonStore } from '@/stores/ai-lesson'

defineOptions({
  name: 'QuestionBank'
})

const { setHideSidebar } = useAILessonStore()

const getPostData = (target, data) => ({
  from: 'ai-learn',
  target,
  data
})
const $router = useRouter()
const $route = useRoute()
const selectCourse = ref({
  course_id: '',
  course_name: '',
  subjectId: 0,
  selectedChecked: [] // 默认选中的目录
})

watch(
  () => $route.fullPath,
  val => {
    console.log(val, 'change full path')
    microData.value = getPostData('change-route-path', {
      fullPath: val
    })
  }
)
const isVis = ref(false)

const initStatus = ref('')
const authStore = useAuthStore()

const { getClassListOfSubject, getTeachingInfo } = authStore
const { nowGlobalSubjectId, nowGlobalStageId, userInfo, nowGlobalRole } =
  storeToRefs(authStore)
const taskStore = useTaskStore()
const { taskList } = storeToRefs(useTaskStore())

const classesTree = ref([])
const initClassList = async () => {
  await getTeachingInfo(nowGlobalRole.value.role_code)
  classesTree.value = await getClassListOfSubject(nowGlobalSubjectId.value)
  console.log('classesTree.value', classesTree.value)
}
watch(
  [
    () => nowGlobalSubjectId.value,
    () => nowGlobalRole.value,
    () => nowGlobalStageId.value
  ],
  async () => {
    await initClassList()
    microData.value = getPostData('update-user-class-info', {
      classesTree: JSON.parse(JSON.stringify(classesTree.value)),
      classId: classesTree.value[0]?.children[0]?.value
    })
  },
  {
    deep: true
  }
)
const init = async () => {
  const res = await authStore.getUserInfoFun()
  await initClassList()
  microData.value = getPostData('init-user-conf', {
    tokenInfo: {
      platform: userInfo.value.platform,
      token: userInfo.value.sessionId,
      userId: userInfo.value.userId,
      userType: userInfo.value.userType
    },
    schoolId: authStore.userInfo.school_id,
    schoolName: authStore.userInfo.school_name,
    classList: res.classList.map(item => ({
      id: item.value,
      name: item.label,
      grade_id: item.grade_id,
      grade_num: item.grade_num,
      is_target: item.is_target
    })),
    classesTree: JSON.parse(JSON.stringify(classesTree.value)),
    subject: nowGlobalSubjectId.value,
    stage: nowGlobalStageId.value,
    questions: JSON.parse(JSON.stringify(taskStore.taskList)),
    parentAppBaseURL: baseURL,
    currentRoute: $route.fullPath
  })
  initStatus.value = true
}
const microData = ref({})
const createVisible = ref(false)
const targetClassParams = ref({
  students: [],
  schoolId: ''
})
const handleClose = () => {
  createVisible.value = false
}

const eventListeners = async e => {
  console.log('eventListeners', e)
  const { target, data, from } = e.detail.data || {}
  if (from !== 'question-bank') return
  switch (target) {
    case 'token-failed':
      ElMessage.info('你的账号在别的地方登录了,请重新登录')
      $router.push('/login')
      break
    case 'add-topic-basket':
      taskStore.setTaskList(data.questions, true)
      break
    case 'remove-topic-basket':
      taskStore.deleteTopicById(data.questions.map(_ => _.topic_id))
      break
    case 'toggle-topic-selector-dialog':
      console.log('toggle-topic-selector-dialog', data)
      iframeTaskMitt.emit('toggle-topic-selector-dialog', data)
      break
    case 'publish-mission':
      isVis.value = true
      selectCourse.value = {
        course_id: data.course_id,
        course_name: data.course_name,
        subjectId: data.subject_id,
        selectedChecked: data.checked_keys
      }
      break
    case 'create-target-class':
      targetClassParams.value = {
        students: data.students,
        schoolId: data.school_id
      }
      createVisible.value = true
      break
    case 'hide-sidebar': {
      setHideSidebar(data.hideSidebar)
      break
    }
  }
}

iframeTaskMitt.on('delete-topic', questions => {
  questions = JSON.parse(JSON.stringify(questions))
  microData.value = getPostData('remove-topic-basket', {
    questions
  })
})
iframeTaskMitt.on('reset-path', info => {
  const { fullPath } = info.item
  microData.value = getPostData('change-route-path', {
    fullPath
  })
})
watch([nowGlobalSubjectId, nowGlobalStageId], () => {
  console.log('change course')
  microData.value = getPostData('update-course-id', {
    subject: nowGlobalSubjectId.value,
    stage: nowGlobalStageId.value
  })
})

const updateTaskList = () => {
  if (document.visibilityState === 'visible') {
    setTimeout(() => {
      microData.value = getPostData('update-question-list', {
        questions: JSON.parse(JSON.stringify(taskList.value))
      })
    }, 100)
  }
}
onMounted(async () => {
  console.log('question-bank 组件mounted加载啦，on mounted~~~~~')
  await init()
  document.addEventListener('visibilitychange', updateTaskList)
})

onUnmounted(() => {
  document.removeEventListener('visibilitychange', updateTaskList)
})
</script>

<style lang="less" scoped>
.question-bank-container {
  height: 100vh;
  width: 100%;
  font-size: 0;
  overflow: hidden;

  .course-iframe {
    height: 100%;
    width: 100%;
    display: block;
    border-style: unset;
  }

  micro-app {
    height: 100%;

    .flex {
      display: flex;
    }
  }
}
</style>
